import 'package:flutter/material.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:oramemo/common/langs/text_key.dart';

class FilterOption {
  final String id;
  final String name;
  bool isSelected;

  FilterOption({
    required this.id,
    required this.name,
    this.isSelected = false,
  });
}

class FilterOverlayDropdown extends StatefulWidget {
  final String title;
  final List<FilterOption> options;
  final bool isMultiSelect;
  final Function(List<FilterOption>) onFilterChanged;
  final Color? activeColor;
  final double? width;

  const FilterOverlayDropdown({
    Key? key,
    required this.title,
    required this.options,
    required this.onFilterChanged,
    this.isMultiSelect = false,
    this.activeColor,
    this.width,
  }) : super(key: key);

  @override
  State<FilterOverlayDropdown> createState() => _FilterOverlayDropdownState();
}

class _FilterOverlayDropdownState extends State<FilterOverlayDropdown> {
  final LayerLink _layerLink = LayerLink();
  OverlayEntry? _overlayEntry;
  bool _isExpanded = false;
  final Color _defaultActiveColor = Colors.blue;

  @override
  void dispose() {
    _removeOverlay();
    super.dispose();
  }

  void _toggleDropdown() {
    if (_isExpanded) {
      _removeOverlay();
    } else {
      _showOverlay();
    }
    setState(() {
      _isExpanded = !_isExpanded;
    });
  }

  void _removeOverlay() {
    _overlayEntry?.remove();
    _overlayEntry = null;
  }

  void _showOverlay() {
    _overlayEntry = _createOverlayEntry();
    Overlay.of(context).insert(_overlayEntry!);
  }

  void _handleOptionTap(FilterOption option) {
    setState(() {
      if (widget.isMultiSelect) {
        option.isSelected = !option.isSelected;
      } else {
        for (var item in widget.options) {
          item.isSelected = item.id == option.id;
        }
        _toggleDropdown(); // 单选时自动关闭
      }
    });

    final selectedOptions = widget.options.where((item) => item.isSelected).toList();
    widget.onFilterChanged(selectedOptions);

    // 强制更新overlay
    _overlayEntry?.markNeedsBuild();
  }

  OverlayEntry _createOverlayEntry() {
    // 获取按钮的RenderBox
    final RenderBox renderBox = context.findRenderObject() as RenderBox;
    final Size size = renderBox.size;

    return OverlayEntry(
      builder: (context) => Stack(
        children: [
          // 半透明背景，点击时关闭
          Positioned.fill(
            child: GestureDetector(
              onTap: _toggleDropdown,
              child: Container(
                color: Colors.black.withOpacity(0.3),
              ),
            ),
          ),
          // 选项列表
          Positioned(
            width: widget.width ?? size.width,
            child: CompositedTransformFollower(
              link: _layerLink,
              showWhenUnlinked: false,
              offset: Offset(0, size.height),
              child: Material(
                elevation: 4,
                child: Container(
                  constraints: BoxConstraints(
                    maxHeight: MediaQuery.of(context).size.height * 0.4,
                  ),
                  decoration: const BoxDecoration(
                    color: Colors.white,
                  ),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      if (widget.isMultiSelect) _buildMultiSelectActions(),
                      Flexible(
                        child: ListView.builder(
                          shrinkWrap: true,
                          padding: EdgeInsets.zero,
                          itemCount: widget.options.length,
                          itemBuilder: (context, index) {
                            return _buildOptionItem(widget.options[index]);
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildMultiSelectActions() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(color: Colors.grey[200]!),
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          TextButton(
            onPressed: () {
              setState(() {
                for (var option in widget.options) {
                  option.isSelected = false;
                }
              });
              widget.onFilterChanged([]);
              _overlayEntry?.markNeedsBuild();
            },
            child: Text(TextKey.filterReset.tr),
          ),
          TextButton(
            onPressed: _toggleDropdown,
            child: Text(TextKey.filterConfirm.tr),
          ),
        ],
      ),
    );
  }

  Widget _buildOptionItem(FilterOption option) {
    return InkWell(
      onTap: () => _handleOptionTap(option),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        decoration: BoxDecoration(
          color: option.isSelected
              ? (widget.activeColor ?? _defaultActiveColor).withOpacity(0.1)
              : Colors.white,
          border: Border(
            bottom: BorderSide(color: Colors.grey[200]!),
          ),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              option.name,
              style: TextStyle(
                fontSize: 14,
                color: option.isSelected
                    ? (widget.activeColor ?? _defaultActiveColor)
                    : Colors.black87,
              ),
            ),
            if (option.isSelected)
              Icon(
                Icons.check,
                color: widget.activeColor ?? _defaultActiveColor,
                size: 18,
              ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return CompositedTransformTarget(
      link: _layerLink,
      child: InkWell(
        onTap: _toggleDropdown,
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(8),
            border: Border(
              bottom: BorderSide(color: Colors.grey[200]!),
            ),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                widget.title,
                style: TextStyle(
                  fontSize: 14,
                  color: _isExpanded
                      ? (widget.activeColor ?? _defaultActiveColor)
                      : Colors.black87,
                ),
              ),
              AnimatedRotation(
                turns: _isExpanded ? 0.5 : 0,
                duration: const Duration(milliseconds: 200),
                child: Icon(
                  Icons.keyboard_arrow_down,
                  color: _isExpanded
                      ? (widget.activeColor ?? _defaultActiveColor)
                      : Colors.grey,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}